package com.own.business.push.module.jpush.client;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.own.business.push.core.base.BasePushClientMethod;
import com.own.business.push.core.model.MessagePushContentModel;
import com.own.business.push.module.jpush.property.JPushProperty;
import com.own.component.common.util.encrypt.EncryptUtil;
import com.own.component.common.util.list.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * JPushClient
 *
 * @author chenxueli
 * @date 2023-11-14 20:12:00
 */
@Slf4j
@Component
public class JPushClient implements BasePushClientMethod {

    @Resource
    public JPushProperty jPushProperty;

    /**
     * 全量推送
     *
     * @param contentModel 内容
     */
    @Override
    public void all(MessagePushContentModel contentModel) {
        var map = buildContent(contentModel);
        map.put("audience", "all");
        var request = HttpRequest.post("https://api.jpush.cn/v3/push")
                .header("Authorization", getAuthorization())
                .contentType("application/json")
                .body(JSON.toJSONString(map))
                .execute();
        var body = request.body();
        log.info("极光推送结果:{}", body);
    }

    /**
     * 注册id推送
     *
     * @param regIdList    注册id列表
     * @param contentModel 内容
     */
    @Override
    public void regId(List<String> regIdList, MessagePushContentModel contentModel) {
        // 别名推送单词最多1000个
        ListUtil.groupList(regIdList, 800).forEach(values -> {
            var map = buildContent(contentModel);
            var regIdMap = new JSONObject();
            regIdMap.put("registration_id", values);
            map.put("audience", regIdMap);
            var request = HttpRequest.post("https://api.jpush.cn/v3/push")
                    .header("Authorization", getAuthorization())
                    .contentType("application/json")
                    .body(JSON.toJSONString(map))
                    .execute();
            var body = request.body();
            log.info("极光推送结果:{}", body);
        });
    }

    /**
     * 别名推送信息
     *
     * @param aliasList    别名列表
     * @param contentModel 内容
     */
    @Override
    public void alias(List<String> aliasList, MessagePushContentModel contentModel) {
        // 别名推送单词最多1000个
        ListUtil.groupList(aliasList, 800).forEach(values -> {
            var map = buildContent(contentModel);
            var aliasMap = new JSONObject();
            aliasMap.put("alias", values);
            map.put("audience", aliasMap);
            var request = HttpRequest.post("https://api.jpush.cn/v3/push")
                    .header("Authorization", getAuthorization())
                    .contentType("application/json")
                    .body(JSON.toJSONString(map))
                    .execute();
            var body = request.body();
            log.info("极光推送结果:{}", body);
        });
    }

    /**
     * 批量单推
     *
     * @param aliasList    别名列表
     * @param contentModel 内容
     */
    private void batchAlias(List<String> aliasList, MessagePushContentModel contentModel) {
        batchPush(
                "https://api.jpush.cn/v3/push/batch/alias/single",
                aliasList,
                contentModel
        );
    }

    /**
     * 批量单推
     *
     * @param regIdList    注册id列表
     * @param contentModel 内容
     */
    private void batchRegId(List<String> regIdList, MessagePushContentModel contentModel) {
        batchPush(
                "https://api.jpush.cn/v3/push/batch/regid/single",
                regIdList,
                contentModel
        );
    }

    /**
     * 批量单推
     *
     * @param api          推送地址
     * @param targetList   推送目标列表
     * @param contentModel 内容
     */
    private void batchPush(String api, List<String> targetList, MessagePushContentModel contentModel) {
        // 获取cid列表
        var cidList = getCidList(targetList.size());
        // 设置别名
        var resultMap = new HashMap<String, JSONObject>();
        for (int i = 0; i < cidList.size(); i++) {
            var cid = cidList.get(i);
            var target = targetList.get(i);
            var map = buildContent(contentModel);
            map.put("target", target);
            resultMap.put(cid, map);
        }
        var request = HttpRequest.post(api)
                .header("Authorization", getAuthorization())
                .contentType("application/json")
                .body(JSON.toJSONString(resultMap))
                .execute();
        var body = request.body();
        log.info("极光推送结果:{}", body);
    }

    /**
     * 获取cid列表
     *
     * @param count 数量
     * @return cid列表
     */
    private List<String> getCidList(int count) {
        var request = HttpRequest.get("https://api.jpush.cn/v3/push/cid?count=" + count)
                .header("Authorization", getAuthorization())
                .contentType("application/json")
                .execute();
        var body = request.body();
        var object = JSON.parseObject(body);
        return object.getJSONArray("cidlist").stream().map(String::valueOf).collect(Collectors.toList());
    }

    /**
     * 构造内容
     *
     * @param contentModel 内容
     * @return 内容
     */
    private JSONObject buildContent(MessagePushContentModel contentModel) {
        var map = new JSONObject();
        map.put("platform", "all");
        var alert = new JSONObject();
        alert.put("alert", contentModel.getContent());
        var android = new JSONObject();
        android.put("alert", contentModel.getContent());
        android.put("title", contentModel.getNotificationTitle());
        android.put("extras", contentModel.getExtras());
        android.put("badge_add_num", 1);
        var ios = new JSONObject();
        ios.put("alert", contentModel.getContent());
        ios.put("extras", contentModel.getExtras());
        ios.put("badge", "+1");
        var tempMap = new JSONObject();
        tempMap.put("alert", alert);
        tempMap.put("android", android);
        tempMap.put("ios", ios);
        map.put("notification", tempMap);
        var options = new JSONObject();
        options.put("apns_production", !jPushProperty.getIsDev());
        map.put("options", options);
        return map;
    }

    /**
     * 获取Authorization
     *
     * @return Authorization
     */
    private String getAuthorization() {
        return "Basic " + EncryptUtil.BASE64.encrypt(jPushProperty.getKey() + ":" + jPushProperty.getSecret());
    }

    /**
     * 推送发送的名称
     *
     * @return 名称
     */
    @Override
    public String name() {
        return "jpush";
    }

}
